<template>
  <div class="edit">
    <div class="edit-list">
      <button @click="$emit('run')">运行</button>
      <button>清空</button>
    </div>
    <div class="edit-box">
      <textarea
        id="textarea"
        :value="code"
        @input="handleInput"
        @keydown.prevent.9="handleKeydown"
      ></textarea>
    </div>
  </div>
</template>

<script>
const code = `<template>
  <div>
    <h1 @click="handleClick">Hello World</h1>
  </div>
</template>
<script>
export default {
  name: '',
  methods: {
    handleClick() {
      alert('hello World')
    }
  }
}
<\/script>
<style lang="less" scoped>
h1 {
  color: rosybrown;
}
</style>`
export default {
  name: 'Edit',
  data() {
    return {
      code,
    }
  },
  mounted() {
    this.$emit('input', this.code)
  },
  methods: {
    handleInput(e) {
      this.code = e.target.value
      this.$emit('input', this.code)
    },
    handleKeydown() {
      let index = this.getCurrPosition('textarea')
      this.code = this.code.substring(0, index) + '  ' + this.code.substring(index)
      // **异步执行才会成功**
      this.$nextTick(() => {
        this.setCurrPosition(index + 2)
      })
      this.$emit('input', this.code)
    },
    // 获取光标位置
    getCurrPosition(id) {
      let textarea = document.getElementById(id)
      var cursurPosition = 0
      if (textarea.selectionEnd) {
        //非IE
        cursurPosition = textarea.selectionEnd
      } else {
        //IE
        // try {
        //   var range = document.selection.createRange()
        //   range.moveStart('character', -textarea.value.length)
        //   cursurPosition = range.text.length
        // } catch (e) {
        //   cursurPosition = 0
        // }
      }
      return cursurPosition
    },
    setCurrPosition(index) {
      let textarea = document.getElementById('textarea')
      textarea.selectionStart = index
      textarea.selectionEnd = index
    }
  },
}
</script>

<style lang="less" scoped>
.edit {
  width: 50%;
  .edit-list {
    padding: 10px;
    background-color: #ccc;
    button {
      height: 40px;
      width: 80px;
      margin: 5px;
    }
  }
  .edit-box {
    position: absolute;
    top: 70px;
    left: 0;
    width: 100%;
    textarea {
      outline: none;
      height: calc(100vh - 70px);
      width: 50%;
    }
  }
}
</style>
